/**
 * mysql 的工具集
 */
export default {getAll_Table}


// 获取数据库中的所有表
async function getAll_Table(DB:DB,library_name:string):Promise<Record<string,any>>{
    if(!DB.select){throw new Error("请先配置数据库")}

    // 获取到所有的表名 [ TextRow { Tables_in_cs: 'user' } ]
    let a = await DB.select({type:"show",sql:'show tables',table:['']},[]);
    let table = {};
    // 遍历表名
    for(let res of a){
        for(let key in res){
            //key是表名，查询表中的key值
            // 获取表中的key键
            let tab = await DB.select({type:"select",table:[''],sql:
                `SELECT
                    k.column_name,
                    k.table_name 
                FROM
                    information_schema.table_constraints t
                    JOIN information_schema.key_column_usage k USING ( constraint_name, table_schema, table_name ) 
                WHERE
                    table_schema='${library_name}'
                AND
                    t.constraint_type = 'PRIMARY KEY' 
                    AND k.table_name = '${res[key]}'`
            },[]);
            
            if(tab.length>=1){
                //获取表中的所有字段
                let field =await DB.select({type:"select",table:[],sql:`select COLUMN_NAME from information_schema.COLUMNS where table_schema='${library_name}' and table_name = '${res[key]}'`});
                field = field.map((res)=>{ return res.COLUMN_NAME;});
                let data = {
                    table_name:tab[0].table_name,
                    table_key:tab[0].column_name,
                    table_field:field,
                }
                table[tab[0].table_name]=data;
            }
        }
    }
    return table;
}